package com.jfinal.ext.sql;

import java.util.ArrayList;
import java.util.List;

import com.jfinal.plugin.activerecord.Db;

public class Criteria extends SqlBuliderFactory {
	private static Criteria criteria;
	@SuppressWarnings("rawtypes")
	private List resultList = null;

	@SuppressWarnings("unchecked")
	public <T> List<T> find() {
		if (sqlNotNull()) {
			resultList = Db.query(sqlStr.toString(), list2Array(values));
			sqlStr = null;
		}
		return resultList;
	}
	

	/**
	 * 获取表中所有字段
	 * 
	 * @param entityName
	 *            实体名称
	 */
	public Criteria(String entityName) {
		sqlStr = new StringBuffer("select * from ").append(entityName).append(
				WHERE_STR);
		values = new ArrayList<Object>();
	}

	/**
	 * 获取表中局部字段
	 * 
	 * @param entityName
	 *            实体名称
	 * @param obtainParams
	 *            提供需要获取值的字段名
	 */
	public Criteria(String entityName, String... obtainParams) {
		sqlStr = new StringBuffer("select ");
		if (obtainParams != null) {
			for (String str : obtainParams) {
				sqlStr.append(str).append(",");
			}
			int lastIndex = sqlStr.lastIndexOf(",");
			sqlStr.delete(lastIndex, lastIndex + 1);
		}
		sqlStr.append(" from ").append(entityName).append(" where 1=1");
		values = new ArrayList<Object>();
	}

	public Criteria addExpr(Criterion expression) {
		if (sqlStr == null) {
			throw new RuntimeException("解析SQL语句出错:无效的SQL语句");
		} else {
			 return criteria;
		}
	}
	/**
	 * 生成SQL
	 * @param expression
	 * @return
	 */
	public String bulidSql(Criterion expression) {
		if (sqlStr == null) {
			throw new RuntimeException("解析SQL语句出错:无效的SQL语句");
		} else {
			 return sqlStr.toString().toLowerCase();
		}
	}
	@SuppressWarnings("rawtypes")
	public static Criteria fromEntityClass(Class clazz) {
		criteria = new Criteria(clazz.getSimpleName());
		return criteria;
	}

	@SuppressWarnings("rawtypes")
	public static Criteria fromEntityClass(Class clazz, String... obtainParams) {
		criteria = new Criteria(clazz.getName(), obtainParams);
		return criteria;
	}

}
